<?php
namespace app;

use think\Controller;
use think\Db;
use think\Request;

class BaseController extends Controller {

	public function __construct()
    {
        parent::__construct();
        $this->request = Request::instance();
    }
	
	/**
	 * 防sql注入
	 * 2018-07-11
	 */
	function daddslashes($string, $force = 0) {     
		if(is_array($string)) {   
			foreach($string as $key => $val) {   
				$string[$key] = $this->daddslashes($val, $force);   
			}   
		} else {   
			$string = addslashes($string);   
		}  
		return $string;   
	}   
	
	/**
	 * 得到参数
	 */
	public function getParam($keyName,$default=null){
		$pvalue = $this->request->param($keyName); 
		$lff = ($pvalue=="");
		$rtt = ($default===null);
		$pvalue = $this->daddslashes($pvalue);
		if($lff && !$rtt){
			return $default;
		}
		return $pvalue;
	}
//	
//	/**
//	 * 得到参数
//	 */
//	public function getParam($keyName,$default){
//		$pvalue = $this->request->param($keyName); 
//		if($pvalue==null){
//			return $default;
//		}
//		
//		$pvalue = $this->daddslashes($pvalue);
//		return $pvalue;
//	}
	
    public function index3()
    {
    		//
    		$aa = $this->getParam("a");
        return 'Hello,World3！';
    }
	
	
	/**
	 * 数据校验
	 * $isAutoResponse:是否自动抛出错误json给前台
	 * $this->validate($newsInstance,["title","category"],["req","req"],["标题","分类"])
	 */
	public function pvalidate($instance,$keys,$formatArray,$tips,$isAutoResponse=true){
		$i = -1;
		$validErrorCode = 1012;
		foreach($keys as $key){
			$i++;
			$curValue = $instance[$key];
			$formatStr = $formatArray[$i];
			
			$formats = explode(",", $formatStr);
			foreach($formats as $format){	
				if($format=='req'){
					if(is_null($curValue) || $curValue==""){
						$errorInfor = $tips[$i]."不能为空";
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}else if($format=='num'){
					if((!is_null($curValue) && $curValue!="") && !preg_match("/^\d*$/",$curValue)) {
						$errorInfor = $tips[$i]."需要数字格式";
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}else if($format=='num>0'){
					if(($curValue!=null && $curValue!="") && (!preg_match("/^\d*$/",$curValue) || $curValue<=0)) {
						$errorInfor = "请设置".$tips[$i];
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}else if($format=='double'){
					if(($curValue!=null && $curValue!="") && !preg_match("/^\d+(\.\d+)?$/",$curValue)) {
						$errorInfor = $tips[$i]."格式输入错误";
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}else if( startWith($format, "len")){
					$lenCount = substr($format, 3);
					if(strlen($curValue)!=$lenCount){
						$errorInfor = $tips[$i]."长度需要".$lenCount."位";
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}else if($format=='phone'){
					if(($curValue!=null && $curValue!="") && !is_phone($curValue)){
						$errorInfor = $tips[$i]."不是有效手机号";
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}else if($format=='nortext'){//只能是普通的字母和数字的组合
					if(($curValue!=null && $curValue!="") && (!preg_match("/^[A-Za-z0-9]+$/",$curValue))) {
						$errorInfor = $tips[$i]."只能是字母或者数字";
						$this->validateError = $errorInfor;
						if($isAutoResponse){
							echo json_encode(array("success"=>0,"code"=>$validErrorCode,"msg"=>$errorInfor));
						}
						return false;
					}
				}
				//继续扩展 int  boolean 等类型
			}
		}
		return true;
	}
	
	/**
	 * generalToken 生成token
	 */
	function generalToken($memberId,$account,$password){
		$curTime = time();
		$expireTime = $curTime+7200;
		$ranNum = mt_rand(1000,9999);
		$str = $memberId."".$ranNum."".$account."".$password."";
		$token = md5($str);
		$token = strtolower($token);
		
		return array("token"=>$token,"expireTime"=>$expireTime);
	}
	
	/**
	 * token认证
	 */
	function checkUserToken(){
    		$token = $this->getParam("userToken");
    		$memberId = $this->getParam("memberId");
			
		if(empty($memberId)){
			echo json_encode(array("success"=>0,"code"=>1015,"msg"=>"缺少memberId标示"));
			return FALSE;
		}
		
//		//先去掉token的认证
//		return TRUE;
			
		if(empty($token)){
			echo json_encode(array("success"=>0,"code"=>1014,"msg"=>"token身份认证失败"));
			return FALSE;
		}
		$userToken = Db::name("t_user_token")->where("memberId",$memberId)->find();
		//token是否相等
		if(empty($userToken) || strtolower($userToken["token"])!=strtolower($token)){
			echo json_encode(array("success"=>0,"code"=>1014,"msg"=>"token身份认证失败"));
			return FALSE;
		}
		
		//token是否过期
		if($userToken["expireTime"]<time()){
			echo json_encode(array("success"=>0,"code"=>1016,"msg"=>"token时间已经过期"));
			return FALSE;
		}
		
		//重新设置token时间  如果要更改7200的话，则
//		$this->member_model->updateById("t_userToken",array("expireTime"=>(time()+7200)),$userToken["id"]);
		Db::name("t_user_token")->where("id",$userToken["id"])->update(["expireTime"=>(time()+7200)]);
		//Db::table('think_user') ->where('id', 1)->update(['name' => 'thinkphp']);
		return TRUE;
		
	}
	
	/**
	 * 签名认证
	 */
	function checkSignatrue(){
		
    		$apikey = $this->getParam("apikey");
    		$timestamp = $this->getParam("timestamp");
    		$sign = $this->getParam("sign");
		
		if(empty($apikey) || empty($timestamp) || empty($sign)){
			echo json_encode(array("success"=>0,"code"=>1007,"msg"=>"apikey，timestamp，sign都不能为空"));
			return FALSE;
		}
		$appSecret = "bodowlKDIFJkgdsdf178374hfjds";
		$fff = time();
		$checkSign = md5("8096".$appSecret.$timestamp);
		if(strtolower($checkSign)!=strtolower($sign)){
			echo json_encode(array("success"=>0,"code"=>1008,"msg"=>"签名校验失败"));
			return FALSE;
		}else{
//			if(abs(time()-$timestamp)>300){
//				echo json_encode(array("success"=>0,"code"=>1009,"msg"=>"签名认证时间失效"));
//				return FALSE;
//			}
		
			return TRUE;
		}
	}

}
